package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.验证手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("请输入正确的手机号");
        }
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3.保存验证码到Redis,并设置过期时间为两分钟
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.发送验证码(模拟)
        log.info("成功发送验证码:{}",code);
        //5.返回
        return Result.ok(code);
    }

    /**
     * 用户登录、注册
     * @param loginForm
     * @param session
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String code = loginForm.getCode();
        String phone = loginForm.getPhone();

        //1.检验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("请输入正确的手机号");
        }
        //2.检验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        log.info("缓存的验证码{}",cacheCode);
        if(!code.equals(cacheCode)){
            return Result.fail("验证码错误");
        }
        //3.查询用户是否存在
        List<User> list = this.lambdaQuery()
                .eq(phone != null,User::getPhone, phone)
                .list();
        User user = new User();
        if(list.isEmpty()){
            user.setPhone(phone);
//            LocalDateTime time = LocalDateTime.now();
//            user.setCreateTime(time);
//            user.setUpdateTime(time);
            user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomString(6));
            this.save(user);
        }else{
            BeanUtils.copyProperties(list.get(0),user);
        }

        log.info("user:{},{}",user.getPhone(),user.getNickName());

        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user,userDTO);
        //生成token的值
        String token = RandomUtil.randomString(6);
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        //将对象转换为hashmap,并将字段值都转换为string类型
        Map<String, Object> userDTOMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)-> fieldValue.toString()));
        //将用户部分信息存入redis
        opsForHash.putAll(RedisConstants.LOGIN_USER_KEY+token,userDTOMap);
        //设置键的过期时间
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL,TimeUnit.SECONDS);
        return Result.ok(token);
    }

    /**
     * 登出
     * @return
     */
    @Override
    public Result logout() {
        String token = request.getHeader("authorization");
        stringRedisTemplate.delete(RedisConstants.LOGIN_USER_KEY+token);
        return Result.ok();
    }
}
